﻿using Consul;
using ED.Common;
using ED.Common.Extensions;
using Microsoft.Extensions.Options;

namespace ED.Cousul
{
    public class ServiceDisConver : IServiceDisConver
    {
        private readonly IOptions<AppCousulConfig> options;
        public ServiceDisConver(IOptions<AppCousulConfig> options)
        {
            this.options = options;
        }
        // 服务发现
        public async Task<ServiceModel> GetService(string serviceName)
        {
            Ensure.NotNullOrEmptyOrWhiteSpace(serviceName, $"serviceName为空！");
            var uri =new Uri(options.Value.ServiceUrl);
            var serviceModel = new ServiceModel();
            using (var consulClient = new ConsulClient(c => 
            {
                c.Address = uri;
            }))
            {
                // 集群？
                var services = consulClient.Catalog.Service(serviceName).Result.Response;
                if (services.Length == 0)
                {
                    // throw new Exception($"未从Consul集群[{uri}]中发现注册的服务[{serviceName}]");
                    // 根据服务名称获取服务
                    var serviceList = await consulClient.Agent.Services();
                    var sercives = serviceList.Response.Where(s => s.Value.Service.Contains(serviceName));
                    if (sercives.Any())
                    {
                        var service = services.Randomize().FirstOrDefault();
                        serviceModel = new ServiceModel
                        {
                            IP = service.Address,
                            Port = service.ServicePort,
                            Name = service.ServiceName,
                            Uri = new Uri("")
                        };
                    }

                }
                else
                {
                    var serviceEndPoint = services.Randomize().FirstOrDefault();
                    serviceModel = new ServiceModel
                    {
                        IP = serviceEndPoint.Address,
                        Port = serviceEndPoint.ServicePort,
                        Name = serviceEndPoint.ServiceName,
                        Uri = new Uri("")
                    };
                }
            }
            return serviceModel;
        }
    }
}
